package com.study.spmongodb.listener;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.data.mapping.context.MappingContext;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.index.IndexOperations;
import org.springframework.data.mongodb.core.index.IndexResolver;
import org.springframework.data.mongodb.core.index.MongoPersistentEntityIndexResolver;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.MongoPersistentEntity;
import org.springframework.data.mongodb.core.mapping.MongoPersistentProperty;
import org.springframework.stereotype.Component;

/**
 * @author MI
 * @version 1.0
 * @date 2020/11/10 16:02
 */
@Component
public class MyListener {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * https://docs.spring.io/spring-data/mongodb/docs/current/reference/html/#mapping.index-creation
     * 单个域类型的编程索引创建
     */
    /*@EventListener(ContextRefreshedEvent.class)
    public void initIndicesAfterStartup() {

        System.out.println(StringUtils.repeat("--", "*", 20));
        System.out.println(StringUtils.center("单个域类型的编程索引创建", 20, "-*"));

        MappingContext<? extends MongoPersistentEntity<?>, MongoPersistentProperty> mappingContext = mongoTemplate
                .getConverter().getMappingContext();

        IndexResolver resolver = new MongoPersistentEntityIndexResolver(mappingContext);

        IndexOperations indexOps = mongoTemplate.indexOps(Personss.class);
        resolver.resolveIndexFor(Personss.class).forEach(indexOps::ensureIndex);
    }*/

    /**
     * 所有初始实体的编程索引创建
     */
    @EventListener(ContextRefreshedEvent.class)
    public void initIndicesAfterStartup() {

        System.out.println(StringUtils.repeat("-", "*", 30));
        System.out.println(StringUtils.center("创建索引", 30, "-"));

        MappingContext<? extends MongoPersistentEntity<?>, MongoPersistentProperty> mappingContext = mongoTemplate
                .getConverter().getMappingContext();
        IndexResolver resolver = new MongoPersistentEntityIndexResolver(mappingContext);
        // consider only entities that are annotated with @Document
        mappingContext.getPersistentEntities()
                .stream()
                .filter(it -> it.isAnnotationPresent(Document.class))
                .forEach(it -> {
                    IndexOperations indexOps = mongoTemplate.indexOps(it.getType());
                    resolver.resolveIndexFor(it.getType()).forEach(indexOps::ensureIndex);
                });
    }
}
